package com.webdemo.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.webdemo.entity.User;
import com.webdemo.util.db.DBUtil;

/*
 * 验证用户登录和新建用户
 */
public class Dao {
	/*
	 * 新建用户
	 */
	public static User addUser(User u) throws SQLException {
		// 获得数据库连接
		Connection conn = DBUtil.getConn();

		// 使用预编译语句
		StringBuilder sql = new StringBuilder();
		sql.append(" insert into user" + "( user_name, password) value("
				+ "?,?)");
		if (sql != null && !"".equals(sql)) {
			PreparedStatement pstate = conn.prepareStatement(sql.toString());
			pstate.setString(1, u.getUserName());
			pstate.setString(2, u.getPassWord());
			pstate.execute();
		}
		System.out.println("添加用户成功！");

		return null;

	}

	/*
	 * 使用用户名查询用户
	 */
	public static User query(String userName) throws SQLException {
		// 获得数据库连接
		Connection conn = DBUtil.getConn();
		// 字符串用于保存SQL语句
		String sql = "";
		// 创建声明
		Statement stat = conn.createStatement();
		// 创建用户
		User u = new User();
		if (userName != null ) {
			sql = "select * from user where user_name ="
					+" '"+userName+"'";

			ResultSet rs = stat.executeQuery(sql);
			while (rs.next()) {
				u.setUserName(rs.getString("user_name"));
				u.setPassWord(rs.getString("password"));
			}
			return u;
		}else {
			return null;
		}
		
	}
	/*
	 * 验证用户登录
	 */
	public static boolean verify(String userName,String passWord) throws SQLException{
		
		if(userName.equals(Dao.query(userName).getUserName())&&
				passWord.equals(Dao.query(userName).getPassWord())){
			return true;
		}else {
			return false;
		}
		
	} 
	
	
	
public static void main(String[] args) throws SQLException {
//		User user = Dao.query("liupeng");
//		if(user.getUserName()!=null&&!"".equals(user.getUserName())){
//		System.out.println(user.toString()+"先生");
//		}
//		else {
//			System.out.println("没有匹配的值");
//		}
//		System.out.println("项目运行完成");
		System.out.println(Dao.verify("lisi", "lisi"));
	}	
}
